<template>
  <div class="box">
    <p class="title">修改产品</p>
    <el-form :model="info" status-icon ref="form" label-width="110px" :rules="rules">
      <el-form-item label="供应商" prop="masterID">
        <el-input v-model="info.masterID" style="display:none"></el-input>
        <el-cascader
          :options="masterList"
          expand-trigger="hover"
          @change="masterChange"
          :value="[info.masterID]"
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="分类" prop="classinfo.classID">
        <el-input v-model="info.classinfo.classID" style="display:none"></el-input>
        <el-cascader
          :options="classList"
          expand-trigger="hover"
          @change="classChange"
          :value="[info.classinfo.parentID, info.classinfo.classID]"
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="info.productName"></el-input>
      </el-form-item>
      <el-form-item label="产品id" prop="productID">
        <el-input v-model.number="info.productID"></el-input>
      </el-form-item>
      <el-form-item label="产品媒体" prop="media" style="margin-bottom:40px">
        <el-upload ref="detailVideoUpload" action="https://api.lktehui.com/admin/upload/upload" name="image" :limit="1"  list-type="fileList" :file-list="startDetailVideoList" style="width:70%; margin-bottom:20px" :on-success="uploadDetailMediaSuccess" :on-remove="uploadDetailVideoRemove" :before-upload="beforeUploadVideo">
          <el-button size="small" type="primary">点击上传视频</el-button>
          <div slot="tip">只能上传1份视频文件，且不超过50mb（可选）</div>
        </el-upload>
        <el-upload ref="detailImgUpload" :multiple="true" action="https://api.lktehui.com/admin/upload/upload" name="image" :limit="5" list-type="picture" :file-list="startDetailImgList" style="width:60%" :on-success="uploadDetailMediaSuccess" :on-remove="uploadDetailImgRemove" :before-upload="beforeUploadImg">
          <el-button size="small" type="primary">点击上传图片</el-button>
          <div slot="tip">最多只能上传5张图片，且不超过500kb（可选）</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="成本价" prop="costPrice">
        <el-input v-model.number="info.costPrice"></el-input>
      </el-form-item>
      <el-form-item label="代理价" prop="agentPrice">
        <el-input v-model.number="info.agentPrice"></el-input>
      </el-form-item>
      <el-form-item label="详情介绍" prop="content">
        <el-input v-model="info.content" style="display:none"></el-input>
        <div id="editor"></div>
      </el-form-item>
      <el-form-item label="首图" prop="titleImg" style="margin-bottom:40px">
        <el-input v-model="info.titleImg" style="display:none"></el-input>
        <el-upload ref="titleImgUpload" action="https://api.lktehui.com/admin/upload/upload" name="image" :limit="1"   :file-list="startTitleImgList" list-type="picture" style="width:60%" :on-success="uploadTitleImgSuccess" :on-remove="uploadTitleImgRemove" :before-upload="beforeUploadImg">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip">只能上传1张图片，且不超过500kb</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="销售价" prop="salePrice">
        <el-input v-model.number="info.salePrice"></el-input>
      </el-form-item>
      <el-form-item label="佣金(返佣价)" prop="commission">
        <el-input v-model.number="info.commission"></el-input>
      </el-form-item>
      <el-form-item label="市场价" prop="marketPrice">
        <el-input v-model.number="info.marketPrice"></el-input>
      </el-form-item>
      <el-form-item label="顺序" prop="sort">
        <el-input v-model.number="info.sort"></el-input>
      </el-form-item>
      <el-form-item label="销售方式" prop="promType">
        <el-select v-model.number="info.promType" placeholder="请选择">
          <el-option label="普通订单" :value="0"></el-option>
          <el-option label="限时抢购" :value="1"></el-option>
          <el-option label="团购" :value="2"></el-option>
          <el-option label="促销优惠" :value="3"></el-option>
          <el-option label="预售" :value="4"></el-option>
          <el-option label="实物类" :value="5"></el-option>
          <el-option label="砍价" :value="6"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产品状态" prop="status">
        <el-select v-model.number="info.status" placeholder="请选择">
          <el-option label="上架" :value="1"></el-option>
          <el-option label="下架" :value="0"></el-option>
          <el-option label="分享专用" :value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="有效期" prop="validity">
        <el-input v-model="info.validity"></el-input>
      </el-form-item>
      <el-form-item label="库存" prop="stock">
        <el-input v-model.number="info.stock"></el-input>
      </el-form-item>
      <el-form-item label="使用规则" prop="useRules">
        <el-input type="textarea" v-model="info.useRules"></el-input>
      </el-form-item>
      <el-form-item class="all-handle-btn-box">
        <el-button type="primary" @click="handleCertain(info)">确定</el-button>
        <router-link class="back-btn" to="/product/list"><el-button @click="$router.back()">返回</el-button></router-link>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      startTitleImgList: [],        //存储进来默认的值，因为默认值的设置形式与原有数据不一致，所以要另外定义
      startDetailImgList: [],
      startDetailVideoList: [],
      detailImgList: [],
      detailVideoList: [],
      agentList: [],
      masterList: [],
      classList: [],
      info: {
        media: [], 
        classinfo: {
          parentID: '',
          classID: ''
        }
      },
      rules: {
        productName: {required: true, message: '产品名称不能为空', trigger: 'change'},
        productID: {required: true, message: '产品id不能为空', trigger: 'change'},
        'classinfo.classID': {required: true, message: '分类不能为空', trigger: 'change'},
        masterID: {required: true, message: '供应商不能为空', trigger: 'change'},
        costPrice: {required: true, message: '成本价不能为空', trigger: 'change'},
        agentPrice: {required: true, message: '代理价不能为空', trigger: 'change'},
        salePrice: {required: true, message: '销售价不能为空', trigger: 'change'},
        marketPrice: {required: true, message: '市场价不能为空', trigger: 'change'},
        commission: {required: true, message: '佣金(返佣价)不能为空', trigger: 'change'},
        promType: {required: true, message: '销售方式还没选择', trigger: 'change'},
        sort: {required: true, message: '顺序还没有选择', trigger: 'change'},
        status: {required: true, message: '状态还没有选择', trigger: 'change'},
        content: {required: true, message: '详情介绍不能为空', trigger: 'change'},
        stock: {required: true, message: '库存还未填写', trigger: 'change'},
        validity: {required: true, message: '有效期不能为空', trigger: 'change'},
        useRules: {required: true, message: '使用规则不能为空', trigger: 'change'},
        titleImg: {required: true, message: '首图不能为空', trigger: 'change'},
        media: {required: true, message: '媒体文件至少有一种', trigger: 'change'}
      }
    }
  },
  methods: {
    handleCertain(info) {
      let _this = this;
      this.getDetailMedia();
      this.$refs.form.validate(bool => {
        if (bool) {
          this.$confirm("确定保存结果么?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            info.classID = info.classinfo.classID;
            //修改操作
            this.$ajax({
              url: "product/setProduct",
              data: {
                app: info
              },
              success(res) {
                if (res.data.code === 1) {
                  _this.$message({
                    type: "success",
                    message: res.data.msg
                  });
                  _this.info = {
                    classinfo: {}
                  };
                  _this.$refs.form.resetFields();
                  _this.$refs.detailVideoUpload.clearFiles();
                  _this.$refs.titleImgUpload.clearFiles();
                  _this.$refs.detailImgUpload.clearFiles();
                  _this.editor.txt.clear();
                  _this.$router.back();
                } else {
                  _this.$message({
                    type: "warning",
                    message: res.data.msg
                  });
                }
              }
            });
          }).catch(() => {});
        }
      });
    },
    beforeUploadImg(file) {
      if (file.size / 1024 > 500) {
        this.$message({
          type: "warning",
          message: "“" + file.name + "”图片超过500kb"
        });
        return false;
      } else if (!/^image/.test(file.type)) {
        this.$message({
          type: "warning",
          message: "“" + file.name + "”不是图片"
        });
        return false;
      }
    },
    beforeUploadVideo(file) {
      if (file.size / 1024 / 1024 > 50) {
        this.$message({
          type: "warning",
          message: "“" + file.name + "”视频超过50mb"
        });
        return false;
      } else if (!/^video/.test(file.type)) {
        this.$message({
          type: "warning",
          message: "“" + file.name + "”不是视频"
        });
        return false;
      }
    },
    uploadDetailMediaSuccess(response, file, fileList) {
      if (response.code === 1) {
        let type = file.raw.type;
        if (/^image/.test(type)) {
          this.detailImgList = fileList;
        } else if (/^video/.test(type)) {
          this.detailVideoList = fileList;
        }
      } else {
        this.$message({
          type: "warning",
          message: response.msg
        });
      }
    },
    //由于编辑操作中的图片不包含file对象，所以返回的参数无法判断是图片还是视频，因此需要分开讨论。
    uploadDetailImgRemove(file, fileList) {
      this.detailImgList = fileList;
    },
    uploadDetailVideoRemove(file, fileList) {
      this.detailVideoList = fileList;
    },
    getDetailMedia() {
      this.info.media = [];
      for (let i = 0;i < this.detailVideoList.length; i++) {
        this.info.media.push({ type: "video", src: this.detailVideoList[i].response ? this.detailVideoList[i].response.content : this.detailVideoList[i].url });
      }
      for (let i = 0;i < this.detailImgList.length; i++) {
        this.info.media.push({ type: "image", src: this.detailImgList[i].response ? this.detailImgList[i].response.content : this.detailImgList[i].url });
      }
    },
    uploadTitleImgSuccess(response, file, fileList) {
      if (response.code === 1) {
        this.$set(this.$data.info, "titleImg", response.content);
      } else {
        this.$message({
          type: "warning",
          message: response.msg
        });
      }
    },
    uploadTitleImgRemove() {
      this.$set(this.$data.info, "titleImg", "");
    },
    masterChange(arr) {
      this.info.masterID = arr[arr.length - 1];
    },
    classChange(arr) {
      this.info.classinfo.parentID = arr[arr.length - 2];
      this.info.classinfo.classID = arr[arr.length - 1];
    }
  },
  created(e) {
    let _this = this;
    let productID = this.$route.query.id;
    //获取供应商id
    this.$ajax({
      url: "product/getMasterList",
      data: {
        app: {
          type: 2
        },
      },
      only: false,
      perfect(con) {
        let arr = con.map((value, index, arr) => {
          return {
            value: value.masterID,
            label: value.trueName
          }
        });
        _this.masterList = arr;
      }
    });
    //获取分类列表
    this.$ajax({
      url:'productclass/getlist',
      perfect(con) { 
        let arr = con.list.map((value, index, arr) => {
          return {
            value: value.classID,
            label: value.className,
            children: value.child.map((value, index, arr) => {
              return {
                value: value.classID,
                label: value.className
              }
            })
          }
        });
        _this.classList = arr;
      }
    });
    let E = require('wangeditor');
    //加载富文本编辑器
    this.$nextTick(() => {
      var editor = new E("#editor");
      editor.customConfig.menus = [
        'head',  // 标题
        'bold',  // 粗体
        'fontSize',  // 字号
        'fontName',  // 字体
        'italic',  // 斜体
        'underline',  // 下划线
        'strikeThrough',  // 删除线
        'foreColor',  // 文字颜色
        'backColor',  // 背景颜色
        'link',  // 插入链接
        'list',  // 列表
        'justify',  // 对齐方式
        'image',  // 插入图片
        'table',  // 表格
        'undo',  // 撤销
        'redo'  // 重复
      ];
      editor.customConfig.uploadImgServer = "https://api.lktehui.com/admin/upload/upload";
      editor.customConfig.zIndex = 2;
      editor.customConfig.uploadFileName = 'image';
      editor.customConfig.uploadImgHooks = {
        customInsert: function (insertImg, result, editor) {
          insertImg(result.content);
        }
      };
      editor.customConfig.onchange = function (html) {
        if (html === "<p><br></p>") {
          html = "";
        }
        _this.$set(_this.$data.info, "content", html);
      };
      editor.customConfig.customAlert = function () {}
      editor.create();
      this.editor = editor;
      //获取产品信息
      this.$ajax({
        url: "product/getInfo",
        data: {
          app: {
            productID: productID
          }
        },
        perfect(con) {
          _this.info = con;
          //为图片媒体添加默认值
          _this.startTitleImgList = [{name: "", url: con.titleImg}]; 
          for (let i = 0; i < con.media.length; i++) {
            if (con.media[i].type === "image") {
              _this.startDetailImgList.push({ name: "", url: con.media[i].src });
              _this.detailImgList.push({ response: { content: con.media[i].src } });
            } else if (con.media[i].type === "video") {
              _this.startDetailVideoList.push({ name: "", url: con.media[i].src });
              _this.detailVideoList.push({ response: { content: con.media[i].src } });
            }
          }
          //为编辑器添加默认值
          _this.editor.txt.html(con.content);
        }
      });
    });
  }
};
</script>

<style scoped>
.el-form {
  width: 50%;
  margin: 0 auto;
}
.title {
  padding: 20px 0;
  font-size: 20px;
  text-align: center;
}
.back-btn {
  margin-left: 10px;
}
.img-box {
  width: 100px;
  height: 100px;
  background-size: cover;
  background-position: center;
  border: 1px solid #f1f1f1;
}
#editor >>> .w-e-menu {
  padding: 0 8px;
}
</style>
